package com.shujiaotong.controller;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shujiaotong.common.R;
import com.shujiaotong.pojo.Card;
import com.shujiaotong.pojo.Category;
import com.shujiaotong.pojo.Shop;
import com.shujiaotong.service.ICategoryService;
import com.shujiaotong.service.IShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/shop")
@Slf4j
public class ShopController {

    @Autowired
    private IShopService shopService;

    @Autowired
    private ICategoryService categoryService;

//    分页

    @GetMapping("page")
    public R page(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String name) {
        log.info("当前页:{},页条数:{},商品名:{}", page, pageSize, name);

        Page<Shop> shopPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Shop> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name), Shop::getShopName, name);

        shopService.page(shopPage, qw);

        shopPage.getRecords().forEach(shop -> {
            // 查询并设置每个 shop 的 categoryName
            Category category = categoryService.getById(shop.getCategoryId());
            shop.setCategoryName(category != null ? category.getName() : "未知类别");
        });

        return R.success(shopPage);
    }

//    新增
    @PostMapping
    public R save(@RequestBody Shop shop){
        log.info("新增商品:{}",shop);
        shopService.save(shop);
        return R.success("新增成功");
    }



// 根据id查询
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        Shop shop = shopService.getById(id);
        if (shop != null) {
            // 查询并设置 shop 的 categoryName
            Category category = categoryService.getById(shop.getCategoryId());
            shop.setCategoryName(category != null ? category.getName() : "未知类别");
        }
        return R.success(shop);
    }

    //    修改
    @PutMapping
    public R update(@RequestBody Shop shop){
        log.info("修改商品:{}",shop);
        shopService.updateById(shop);
        return R.success("修改成功");
    }

    //    删除
    @DeleteMapping
    public R delete(Long id) {
        boolean b = shopService.removeById(id);
        return b ? R.success("删除成功") : R.error("删除失败");
    }

    // 根据 categoryId 获取商品分类名称
    @GetMapping("getShopByCategoryId/{id}")
    public R getShopByCategoryId(@PathVariable Long id){
        LambdaQueryWrapper<Shop> qw = new LambdaQueryWrapper<>();
        qw.eq(Shop::getCategoryId,id);
        return R.success(shopService.list(qw));
    }

}
